import { ForbiddenException, HttpException, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
// import { getUserDto } from 'src/user/dto/get-user.dto';
// import { User } from 'src/user/user.entity';
import { UserService } from '../user/user.service';
import * as argon2 from 'argon2';
import { SigninUserDto } from './dto/signin-user.dto';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private readonly jwtService: JwtService
  ){}

  // 登录
  async signin(username: string, password: string): Promise<{token: string}> {
    // const res = await this.userService.findAll({ username } as getUserDto)
    const user = await this.userService.find(username)

    if(!user){
      throw new ForbiddenException('用户不存在，请注册');
    }

    // 验证用户密码
    const isPasswordValid = await argon2.verify(user.password, password)

    if(!isPasswordValid){
      throw new ForbiddenException('用户名或密码错误');
    }

    // if(user?.password !== password){
    //   throw new UnauthorizedException()
    // }

    // 生成 token
    const payload = { sub: user.id, username: user.username }
    const token = await this.jwtService.signAsync(payload)

    return {
      token
    };
  }

  // 注册
  async signup(dto: SigninUserDto){
    const { username, password, avatar, nickname, active } = dto;
    const user = await this.userService.find(username);
    if(user){
      throw new ForbiddenException('用户已存在');
    }
    return this.userService.create({username, password, avatar, nickname, active})
  }
}
